//app.js
import api from "/utils/apis.js";
import message from "/utils/message.js"
import util from "/utils/util.js"

App({
  onLaunch: function() {
    let self = this;


    self.uploadUserinfo()
  },

  uploadUserinfo() {
    let self = this
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            withCredentials: true,
            success(res) {
              console.log(res)
              self.globalData.rawData = res.encryptedData;
              self.globalData.signature = res.signature;
              self.globalData.iv = res.iv

              wx.checkSession({
                success() {
                  //session_key 未过期，并且在本生命周期一直有效
                  //调用自己平台的登录
                  self.wxlogin();
                },
                fail() {
                  // session_key 已经失效，需要重新执行登录流程
                  self.wxlogin();
                }
              })
            }
          })
        }
      }
    })
  },

  wxlogin() {
    let self = this

    wx.login({
      success(res) {
        if (res.code) {
          if (res.errMsg == "login:ok") {
            self.globalData.authCode = res.code
            self.loginAction()
          }
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  loginAction() {
    let self = this;

    let param = {
      code: self.globalData.authCode,
      grantType: "wechat_mini_app",
      login: '',
      rawData: self.globalData.rawData,
      signature: self.globalData.signature,
      iv: self.globalData.iv
    };
    wx.request({
      url: api.loginApi,
      method: "POST",
      data: param,
      header: {
        "content-type": "application/json"
      },
      success(res) {
        if (res.statusCode == "200") {
          let token = res.data.id_token;
          try {
            wx.setStorageSync("authorization", token);
          } catch (e) {
            console.log(e);
          }
        } else {
          if (res.data.message == 'CODE不合法') {
            self.wxlogin()
          } else {
            message.showInfo(
              res.data.message ? res.data.message : "网络连接异常"
            );
          }
        }
      }
    });
  },
  globalData: {
    authCode: '',
    userInfo: '',
    rawData: null,
    signature: null,
    inviteUserId: null,
    iv: null
  }
})